class Correlation < ActiveRecord::Base
  belongs_to :category, :foreign_key=>"category_id"
  
  def self.update_correlation(object_1,object_2)
    if thecategory=Category.find_category(object_2)
      if thecategory==Category.find_category(object_1) && (not object_1.id==object_2.id)
        thecorrelation=Correlation.find(:first,
                                        :conditions => ["category_id = ? and obj_a_id = ? and obj_b_id = ?" ,thecategory.id,object_1.id,object_2.id])||Correlation.create_correlation(thecategory,object_1,object_2)
        thecorrelation.user_cor_value += 1
        thecorrelation.save
        return thecorrelation
      else
        return nil
      end
    end
  end
  
  def self.create_correlation(thecategory,object_1,object_2)
    object_1_key=[]
    object_2_key=[]
    new_correlation=Correlation.new
    new_correlation.category=thecategory
    new_correlation.obj_a_id=object_1.id
    new_correlation.obj_b_id=object_2.id
    new_correlation.obj_a_name= thecategory.id==4 ? object_1.title : object_1.name
    new_correlation.obj_b_name= thecategory.id==4 ? object_2.title : object_2.name
    new_correlation.user_cor_value=0
    Index.find(:all,
               :conditions => ["category_id = ? and obj_id = ?",thecategory.id,object_1.id]).each {|index| object_1_key<<index.keyword_id}
    Index.find(:all,
               :conditions => ["category_id = ? and obj_id = ?",thecategory.id,object_2.id]).each {|index| object_2_key<<index.keyword_id}
    object_1_key = object_1_key & object_2_key
    new_correlation.keyword_cor_value=object_1_key.length
    return new_correlation
  end
  
end
